<template>
  <Modal
    v-model="visiable"
    :closable="false"
    :mask-closable="false"
    title="重置密码"
  >
    <Form ref="formValidate" :model="formFields" :rules="ruleValidate" :label-width="90" style="width: 400px">
      <FormItem label="新密码" prop="password">
        <Input type="password" v-model="formFields.password" />
      </FormItem>
      <FormItem label="确认密码" prop="confirmPassword">
        <Input type="password" v-model="formFields.confirmPassword" />
      </FormItem>
    </Form>
    <div slot="footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleOk" :loading="isLoading">确定</Button>
    </div>
  </Modal>
</template>

<script>
import {resetPassword} from '@/api/user-manage.js'

export default {
  name: 'resetPasswordModal',
  props: ['isShowModal', 'rowData'],
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.formFields.confirmPassword !== '') {
          // 对第二个密码框单独验证
          this.$refs.formValidate.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.formFields.password) {
        callback(new Error('您输入的输入的两次密码不匹配!'))
      } else {
        callback()
      }
    }
    return {
      isLoading: false,
      visiable: this.isShowModal,
      userCode: this.rowData,
      formFields: {
        password: '',
        confirmPassword: ''
      },
      ruleValidate: {
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validatePassCheck, trigger: 'blur' }]
      }
    }
  },
  watch: {
    isShowModal (val) {
      this.visiable = val
    },
    rowData (val) {
      this.userCode = val.userCode
    }
  },
  methods: {
    handleOk () {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          const results = this.formFields
          results.userCode = this.userCode
          resetPassword(results).then((response) => {
            const { data } = response
            if (data.code === 2000) {
              this.$Message.success('密码重置成功')
              this.handleCancel()
            } else {
              this.$Message.error(data.msg || '系统错误，请稍后再试')
            }
            this.isLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.isLoading = false
      this.$refs['formValidate'].resetFields() // 重置form表单
      this.$emit('closeModal')
    }
  }
}
</script>
